import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {AppModule} from "./app.module";


@Injectable({
  providedIn: 'root'
})
export class TokenService {


  constructor(private http: HttpClient) {

  }


  private url = AppModule.BASE_NET_URL + '/auth/login';

  public getToken() {

    this.http.post(this.url, {}, {params: new HttpParams().set('username', localStorage.getItem('name')).set('password', localStorage.getItem('word'))}).subscribe(data => {
      localStorage.removeItem('token');

      localStorage.setItem('token', data['token']);

    });
  }

  refreshToken() {
    setInterval(this.getToken(), 1000 * 60 * 5);

  }

  // intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  //   //
  //   // const clonedRequest = req.clone({
  //   //   headers: req.headers.set('Authorization', 'Bearer ' + this.getToken())
  //   // });
  //   // req.headers.set('Authorization', 'Bearer ' + this.getToken());
  //   const dummyrequest = req.clone({
  //     setHeaders: {
  //       'Authorization': 'Bearer ' + this.getToken()
  //     }
  //   });
  //   // console.log("new headers", clonedRequest.headers.keys());
  //   return next.handle(dummyrequest);
  //   /*.do((event: any) => {
  //   console.log(event);
  //     if (event instanceof HttpResponse) {
  //       if (event.status === 403) {
  //         // 权限处理
  //         console.log('401权限受限');
  //       }else if (event.status === 200) {
  //         // 业务层级错误处理
  //         console.log('200业务层级错误处理');
  //       }else if (event.status === 404) {
  //         console.log('404接口不存在。');
  //       }
  //     }
  //     return event;
  //   });*/
  // }
  // public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  //   this.slimLoadingBarService.start();
  //   const token = localStorage.getItem(global.tokenName);
  //
  //   if (request.url.startsWith(environment.baseUrl)) {
  //     request = request.clone({
  //       setHeaders: {
  //         Authorization: token != null ? token : '',
  //         'Content-Type': 'application/json'
  //       }
  //     });
  //   }
  //
  //   return next.handle(request).do(
  //     (event: HttpEvent<any>) => {
  //       if (event instanceof HttpResponse) {
  //         this.slimLoadingBarService.complete();
  //         if (!request.url.includes('auth-tokens')) { // my api endpoint to avoid to trigger the interceptor when I refresh the token.
  //           try {
  //             const expirationLeft = this.jwtHelper.getTokenExpirationDate(token).getTime() - Date.now();
  //             if (expirationLeft > 0) {
  //               if (expirationLeft < (this.offsetSeconds * 1000) && !this.isUpdating) {
  //                 this.updateAuthToken();
  //               }
  //             }
  //           } catch (e) {
  //           }
  //         }
  //       }
  //     },
  //     (error: any) => {
  //       this.slimLoadingBarService.complete();
  //       if (error instanceof HttpErrorResponse) {
  //         if (error.status === 401) {
  //           localStorage.clear();
  //           this.socketService.close();
  //           for (const sub of this.subscriptions) {
  //             sub.unsubscribe();
  //           }
  //           this.router.navigateByUrl('/sign-in');
  //         }
  //       }
  //     }
  //   );
  // }
  //
  // /**
  //  * Updates the token if it will expire and the current user is navigating.
  //  */
  // private updateAuthToken(): void {
  //   this.isUpdating = true;
  //   const authTokenRepository = this.injector.get(AuthTokenRepository);
  //   this.subscriptions.push(authTokenRepository.getAuthTokenUpdate().subscribe(
  //     (authToken: AuthToken) => {
  //       localStorage.setItem(global.tokenName, authToken.value);
  //       this.isUpdating = false;
  //     }
  //   ));
  // }
}
